package pvn.com;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.global.Formatter;

import pvn.com.utils.DateConverter;
import pvn.com.utils.ParseNumbers;
import net.rim.device.api.util.Arrays;
import net.rim.device.api.util.MathUtilities;
import net.rim.device.api.util.SimpleSortingVector;

public class ParamsStorage {

    public static String serverHost = "";
    public static int serverPort = 7676;
    public static String sLogin = "";
    public static String sPassword = "";
    public static ServerConnection server = null;
    public static String currency = "";
    public static Hashtable Symbols = new Hashtable(150);
    public static Hashtable ExtSymbols = new Hashtable(25);
    public static Hashtable Prices = new Hashtable(150);
    public static SimpleSortingVector SymGroups = new SimpleSortingVector();
    public static Vector FavSymbols = new Vector();
    public static double Balance = 0.0D;
    public static double Margin = 0.0D;
    public static double SumSwap = 0.0D;
    public static double SumSwapOrig = 0.0D;
    public static double SumProfit = 0.0D;

    public static Formatter f2N = new Formatter("en-GB");
    public static Formatter fN = new Formatter("en-GB");

    public static String[] instruments = { "#NG", "#CL", "#NKD", "#EP", "#ENQ", "#YM", "#W", "#C",
            "#S", "#FDX", "#FCE", "#FSMI", "#FFI", "#EX", "#FT" };

    public static String[] instr_term_currencies = { "USD", "USD", "USD", "USD", "USD", "USD",
            "USD", "USD", "USD", "EUR", "EUR", "CHF", "GBP", "EUR", "EUR" };

    public static String GetBaseUrl() {
        String base_url = "";
        return base_url;
    }

    public static void ReInit() {
        ExtSymbols.clear();
        Symbols.clear();
        SymGroups.removeAllElements();
        Prices.clear();
        currency = "";
        serverHost = "";
        serverPort = 7676;
        Balance = 0.0D;
        Margin = 0.0D;
        SumSwap = 0.0D;
        SumSwapOrig = 0.0D;
        SumProfit = 0.0D;
    }

    public static boolean isConnected() {
        return currency != "";
    }

    public static void PutExtSymbols(String[] SymbolArgs) {
        ExtSymbols.clear();
        int cnt = SymbolArgs.length;
        for (int i = 1; i < cnt; i++) {
            if (SymbolArgs[i] == "$")
                continue;
            String key = SymbolArgs[i];
            ExtSymbols.put(key, key);
        }
    }

    public static void PutSymbols(String[] symbol_args) {
        int cnt = symbol_args.length;
        for (int i = 1; i < cnt - 1; i += 10) {
            if (symbol_args[i].compareTo("$") == 0)
                continue;
            SymbolInfo sym = new SymbolInfo();
            sym.OrderBy = i;
            sym.Symbol = symbol_args[i];
            sym.Desc = symbol_args[(i + 1)];
            sym.GroupId = Integer.parseInt(symbol_args[(i + 2)]);
            sym.Digits = Integer.parseInt(symbol_args[(i + 3)]);
            sym.TradeMode = Integer.parseInt(symbol_args[(i + 4)]);
            sym.ProfitMode = Integer.parseInt(symbol_args[(i + 5)]);
            sym.StopsLevel = Integer.parseInt(symbol_args[(i + 6)]);
            sym.ContractSize = ParseNumbers.atof(symbol_args[(i + 7)]);
            sym.TickValue = ParseNumbers.atof(symbol_args[(i + 8)]);
            sym.TickSize = ParseNumbers.atof(symbol_args[(i + 9)]);
            sym.DepositCurrency = currency;
            sym.TermCurrency = null;

            sym.isExt = ExtSymbols.containsKey(sym.Symbol);

            Symbols.put(sym.Symbol, sym);
        }
        Enumeration enumerator = Symbols.elements();

        while (enumerator.hasMoreElements()) {
            SymbolInfo sym = (SymbolInfo) enumerator.nextElement();
            if (sym.ProfitMode != 0) {
                switch (sym.ProfitMode) {
                case 1:
                    if ((sym.Symbol.equals("GOLDEURO")) || (sym.Symbol.equals("SILVEREURO"))) {
                        sym.TermCurrency = "EUR";
                    } else {
                        sym.TermCurrency = "USD";
                    }
                    break;
                case 2:
                    sym.TermCurrency = "USD";

                    int symbol_len = sym.Symbol.length();
                    String symbol_part = sym.Symbol.substring(0, symbol_len - 2);

                    int instr_index = Arrays.getIndex(instruments, symbol_part);
                    String symbol_term_cur = instr_term_currencies[instr_index];

                    if ((symbol_term_cur.equals("USD")) || (symbol_term_cur.length() <= 0))
                        break;
                    sym.TermCurrency = symbol_term_cur;
                }

                if (sym.TermCurrency.compareTo(sym.DepositCurrency) == 0) {
                    sym.Conv1 = new Conversion();
                    sym.Conv1.Constant = true;
                } else {
                    sym.Conv1 = GetConversion(sym.TermCurrency, sym.DepositCurrency);
                }
            } else {
                sym.Conv1 = Pair2Cur(sym.Symbol, sym.DepositCurrency);
                if (!sym.Conv1.IsEmpty()) {
                    continue;
                }
                sym.Conv1 = Pair2Cur(sym.Symbol, "USD");
                if (sym.Conv1.IsEmpty())
                    continue;
                sym.Conv2 = Pair2Cur(sym.Conv1.Pair, sym.DepositCurrency);
            }
        }
    }

    public static Conversion Pair2Cur(String pair, String cur) {
        String p1 = pair.substring(0, 3);
        String p2 = pair.substring(3);
        if (p2.compareTo(currency) == 0) {
            Conversion Conv = new Conversion();
            Conv.Constant = true;
            Conv.Pair = (p2 + p2);
            return Conv;
        }
        Conversion Conv = GetConversion(p2, cur);
        if (!Conv.IsEmpty()) {
            return Conv;
        }
        Conv = GetConversion(p1, cur);
        if (!Conv.IsEmpty()) {
            Conv.ReversePrevious = true;
            return Conv;
        }
        return Conv;
    }

    public static Conversion GetConversion(String cur1, String cur2) {
        Conversion Conv = GetConversionInternal(cur1, cur2);
        return Conv;
    }

    public static Conversion GetConversionInternal(String cur1, String cur2) {
        Conversion Conv = new Conversion();
        String forward = cur1 + cur2;
        String reverse = cur2 + cur1;
        if (Symbols.containsKey(forward)) {
            Conv.Pair = forward;
            Conv.Divide = false;
        } else if (Symbols.containsKey(reverse)) {
            Conv.Pair = reverse;
            Conv.Divide = true;
        }
        return Conv;
    }

    public static void ProcessMargin(String[] margin) {
        Balance = ParseNumbers.atof(margin[1]);
        Margin = ParseNumbers.atof(margin[2]);
    }

    public static void PutPrices(String[] prices_args) {
        int cnt = prices_args.length;

        for (int i = 1; i < cnt - 1; i += 8) {
            if (prices_args[i].compareTo("$") == 0)
                continue;
            TickData dat = new TickData();
            dat.Symbol = prices_args[i];
            dat.Bid = prices_args[(i + 1)];
            dat.Ask = prices_args[(i + 2)];
            dat.direction = (prices_args[(i + 3)].compareTo("U") == 0 ? 1 : 0);
            dat.Max = prices_args[(i + 6)];
            dat.Min = prices_args[(i + 7)];

            dat.lastUpdate = DateConverter.Convert(prices_args[(i + 5)]);

            Prices.put(dat.Symbol, dat);
        }
    }

    public static String formatPrice(double p, String symbol) {
        int digits = 5;
        if (Symbols.containsKey(symbol)) {
            digits = ((SymbolInfo) Symbols.get(symbol)).Digits;
        }
        String res = "";
        try {
            if (p == 0.0D) {
                int powered = (int) MathUtilities.pow(10.0D, digits);
                res = "0." + String.valueOf(powered).substring(1);
            } else {
                double powered = MathUtilities.pow(10.0D, digits);

                int iPart = (int) ((p + 0.1D / powered) * powered);
                res = String.valueOf(iPart);
                if (p < 1.0D) {
                    res = "0000000000".substring(10 - (digits + 1 - res.length())) + res;
                }
                res = res.substring(0, res.length() - digits) + "."
                        + res.substring(res.length() - digits);
            }
            if ((p > 0.0D) && (p < 1.0D) && (!res.startsWith("0")))
                res = "0" + res;
            return res;
        } catch (Exception e) {
            res = fN.formatNumber(p);
        }

        return res;
    }

    public static String formatProfit(double p) {
        boolean isNeg = p < 0.0D;
        if (isNeg)
            p = -p;
        p = (int) (p * 100.0D + 0.5D) / 100.0D;
        String res_temp = f2N.formatNumber(p, 2);
        String res = res_temp.substring(res_temp.length() - 3);
        int c = 1;
        for (int i = res_temp.length() - 4; i >= 0; i--) {
            res = res_temp.charAt(i) + res;
            if ((c == 3) && (i > 0)) {
                c = 1;
                res = " " + res;
            } else {
                c++;
            }
        }
        if (isNeg)
            res = "-" + res;
        return res;
    }

    public static boolean validateFloat(String text) {
        double fRes = 0.0D;
        try {
            fRes = Double.parseDouble(text);
        } catch (Exception ex) {
            return false;
        }

        return fRes >= 0.0D;
    }

    public static boolean validateInt(String text) {
        int iRes = 0;
        try {
            iRes = Integer.parseInt(text);
        } catch (Exception ex) {
            return false;
        }

        return iRes >= 0;
    }
}
